<template>
  <div>
    <!--    &lt;!&ndash;    <el-button type="primary" @click="delrouterall()">click</el-button>&ndash;&gt;-->
    <!--    <el-input style="width: 200px; margin: 0 10px" placeholder="请输入用户名" suffix-icon="el-icon-search"-->
    <!--              v-model="username"/>-->

    <!--    <el-button type="primary" @click="search">搜索 <i-->
    <!--        class="el-icon-search"></i></el-button>-->

    <div>
      <el-button size="small" plain type="primary" style=" margin: 10px 3px 20px 10px"
                 @click="showNewUserForm">新增用户 <i
          class="el-icon-circle-plus"></i></el-button>

      <!--      <el-button  size="small" type="danger"  style=" margin: 0px 3px 0px "-->
      <!--                 @click="showNewUserForm">批量删除<i-->
      <!--          class="el-icon-circle-plus"></i></el-button>-->
      <!--      <el-button type="danger" style="margin: 10px" @click="handleDelBatch">批量删除<i-->
      <!--          class="el-icon-remove-outline"></i></el-button>-->
      <div style="float: right">
        <el-cascader
            style="margin-left: 10px; width: 255px"
            placeholder="请选择单位"
            ref="dwref"
            v-model="dwid"
            @change=""
            :options="dwoptions"
            :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id', emitPath: false }"
            clearable>
        </el-cascader>
        <el-input style="width: 200px; margin: 0 10px 10px 10px" placeholder="请输入用户名"
                  suffix-icon="el-icon-search"
                  v-model="username"/>

        <el-button type="primary" @click="search">搜索 <i
            class="el-icon-search"></i></el-button>
      </div>
    </div>

    <el-dialog title="新增用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="formrules" ref="saveform">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="xm">
          <el-input v-model="form.xm" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="单位" :label-width="formLabelWidth" prop="dw">
          <el-cascader
              style="width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="form.dw"
              @change=""
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id',emitPath: false }"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-checkbox-group v-model="checkedRoles">
            <el-checkbox v-for="role in roles" :label="role.roleId" :key="role.roleId">{{ role.roleName }}({{role.dwObj.dwname}})</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="超级管理员" :label-width="formLabelWidth" v-show="currentUser.superadmin">
          <el-checkbox v-model="form.superadmin">
          </el-checkbox>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="编辑用户" :visible.sync="editdialogFormVisible">
      <el-form :model="editform" :rules="editformrules" ref="editform">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="editform.username" autocomplete="off"></el-input>
        </el-form-item>
        <!--        <el-form-item label="密码" :label-width="formLabelWidth">-->
        <!--          <el-input v-model="editform.password" autocomplete="off"></el-input>-->
        <!--        </el-form-item>-->


        <el-form-item label="姓名" :label-width="formLabelWidth" prop="xm">
          <el-input v-model="editform.xm" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="单位" :label-width="formLabelWidth" prop="dw">
          <el-cascader
              style="width: 255px"
              placeholder="请选择单位"
              ref="dwref"
              v-model="editform.dw"
              @change=""
              :options="dwoptions"
              :props="{ expandTrigger: 'hover', checkStrictly: true, label: 'dwname', value:'id',emitPath: false }"
              clearable></el-cascader>
        </el-form-item>
        <!--        <el-form-item label="角色" :label-width="formLabelWidth">-->
        <!--          <el-checkbox-group v-model="checkedRoles">-->
        <!--            <el-checkbox v-for="role in roles" :label="role.roleId" :key="role.roleId">{{ role.roleName }}</el-checkbox>-->
        <!--          </el-checkbox-group>-->
        <!--        </el-form-item>-->
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-checkbox-group v-model="checkedRoles">
            <el-checkbox v-for="role in roles" :label="role.roleId" :key="role.roleId">{{ role.roleName }}({{role.dwObj.dwname}})</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="超级管理员" :label-width="formLabelWidth" v-show="currentUser.superadmin">
          <el-checkbox v-model="editform.superadmin">
          </el-checkbox>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEidt()">确 定</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" style="margin: 0px 10px 10px; width: 1600px" border stripe>
      <!--      <el-table-column prop="id" label="ID" width="140">-->
      <!--      </el-table-column>-->
      <el-table-column label="序号" type="index" width="50">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="100">
      </el-table-column>
      <el-table-column prop="xm" label="姓名" width="100">
      </el-table-column>
      <el-table-column prop="dwObj.dwname" label="单位" width="180">
      </el-table-column>
      <el-table-column prop="roleNameList" label="角色" width="800">
      </el-table-column>
      <el-table-column prop="superadmin" label="超级管理员" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.superadmin ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="#" label="操作">
        <template slot-scope="scope">

          <el-button size="small" type="primary" plain @click="showEditForm(scope.row)">编辑 <i
              class="el-icon-edit"></i></el-button>
          <!--              <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>-->

          <el-popconfirm
              style="margin: 0 10px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="handleDel(scope.row.id)"
          >
            <el-button size="small" plain type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i>
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="padding: 5px">

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <router-view/>
  </div>

</template>
<script>
import service from "@/utils/request";
import ElementUI from "element-ui";

import VueRouter from 'vue-router'
import HomeView from "@/views/HomeView.vue";


export default {
  created() {
    this.currentUser = JSON.parse(sessionStorage.getItem('user'));
    this.load();
  },
  data() {
    var checkUserName = (rule, value, callback) => {
      // if (!value) {
      //   return callback(new Error('用户名不能为空'));
      // }
      service.get('/user/checkSameUserName', {
        params: {
          userName: value
        }
      }).then(response => {
        console.log(response)
        if (response.data.code == 20000) {
          callback();
        } else if ((response.data.code == 20009)) {
          callback(new Error(response.data.message));
        }
      })
    };
    var checkEditUserName = (rule, value, callback) => {

      service.get('/user/checkEditSameUserName', {
        params: {
          id: this.editform.id,
          userName: value
        }
      }).then(response => {
        console.log(response)
        if (response.data.code == 20000) {
          callback();
        } else if ((response.data.code == 20009)) {
          callback(new Error(response.data.message));
        }
      })

    };

    return {
      // tableData: Array(15).fill(item),
      currentUser: null,
      dwid: null,
      dwoptions: [],
      roles: null, //所有的角色信息
      checkedRoles: [],
      defaultProps: {
        label: 'name'
      },
      username: '',
      roleId: null,
      menucheckedkeys: null,
      tableData: [],
      pageSize: 10,
      total: 100,
      currentPage: 1,
      // roleName: null,
      menudata: [],

      dialogFormVisible: false,
      editdialogFormVisible: false,
      form: {
        username: '',
        password: '',
        roleId: '',//淘汰
        roleList: [],//save时候用
        superadmin: false,
        dw: null,
        xm: null
      },
      editform: {
        id: '',
        username: '',
        // password: '',
        roleid: '',//淘汰
        roleList: [],//update时候用
        superadmin: false,
        dw: null,
        xm: null
      },
      formLabelWidth: '120px',
      formrules: {
        username: [
          {validator: checkUserName, trigger: 'change'},
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        xm: [
          {type: 'string', required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        dw: [
          {required: true, message: '请选择单位', trigger: 'blur'}
        ]
      },
      editformrules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {validator: checkEditUserName, trigger: 'change'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        xm: [
          {type: 'string', required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        dw: [
          {required: true, message: '请选择单位', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    delrouterall() {
      const newRouter = new VueRouter({
        routes: [
          ...dyroutes
        ]
      })
      console.log(this.$router.getRoutes())
      console.log(this.$router.options.routes)
      // this.$router.options.routes = []

      this.$router.matcher = newRouter.matcher
      //
      // console.log(this.$router.getRoutes())
    },

    load() {
      service.get('/dw/getAll', {}).then(
          response => {
            if (response.data.code == 20000) {
              this.dwoptions = response.data.data
            }
          }
      )
      service.get('/user/getpage1', {
        params: {
          dw: this.dwid,
          username: this.username,
          pagesize: this.pageSize,
          pagenum: this.currentPage,
        }
      }).then(response => {
            if (response.data.code == 20000) {
              this.tableData = response.data.data.records;
              for (let i = 0; i < this.tableData.length; i++) {
                this.tableData[i].roleNameList = this.tableData[i].roleList.map(item => item.roleName).join(',')
              }
              this.total = response.data.data.total;
              this.currentPage = response.data.data.current;
              this.pageSize = response.data.data.size;
            }
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
      service.get('/role/getlist', {
        params: {}
      }).then(response => {
            this.roles = response.data
            // this.dialogFormVisible = true
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
    },
    showNewUserForm() {
      service.get('/role/getlist', {
        params: {}
      }).then(response => {
            this.roles = response.data
            this.form.username = ''
            this.form.password = ''
            // this.form.roleId = ''
            // this.form.roleList = []
            this.form.superadmin = false
            this.form.dw = null
            this.form.xm = null
            this.checkedRoles = []
            this.dialogFormVisible = true
            this.$nextTick(() => {
              this.$refs["saveform"].clearValidate()
            })

          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.load()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.load()
    },

    // 保存,未保存角色信息，重写
    // handleSave() {
    //   service.post('/user/save', this.form).then(response => {
    //     if (response.data.code == 20000) {
    //       this.$message.success('success!');
    //       this.dialogFormVisible = false
    //       this.load()
    //     } else {
    //       this.$message.error("error")
    //       this.dialogFormVisible = false
    //     }
    //   })
    // },

    handleSave() {
      this.$refs["saveform"].validate(async (valid) => {
        if (!valid) {
          return
        }
        try {
          this.form.roleList = []
          for (let i = 0; i < this.checkedRoles.length; i++) {
            this.form.roleList.push({
              roleId: this.checkedRoles[i],
              roleName: ''
            })
          }
          let saveform = Object.assign({}, this.form)

          let res = await service.post('/user/savewithroles', saveform)
          if (res.data.code == 20000) {
            this.$message.success('保存成功！')
          } else {
            this.$message.error("保存失败！")
          }
          this.dialogFormVisible = false
          this.load()
        } catch (e) {
          console.log(e)
          this.dialogFormVisible = false
          this.$message.error("保存失败！")
        }
      })


    },

    showEditForm(row) {
      // console.log('row:')
      // console.log(row)

      service.get('/role/getlist', {
        params: {}
      }).then(response => {
            this.roles = response.data
            this.editform.id = row.id
            this.editform.username = row.username
            this.editform.password = null
            this.editform.roleid = row.roleId//淘汰的字段

            this.editform.superadmin = row.superadmin
            this.editform.dw = row.dw
            this.editform.xm = row.xm
            this.checkedRoles = []

            if (row.roleList) {
              this.checkedRoles = row.roleList.map(item => item.roleId)
            }
            this.editdialogFormVisible = true
            this.$nextTick(() => {
              this.$refs["editform"].clearValidate()
              console.log(this.editform.username)
              console.log(row.username)
            })
          },
          error => {
            ElementUI.Message({
              message: error.message,
              type: 'error'
            })
          }
      );
    },
    handleEidt() {
      this.$refs["editform"].validate(async (valid) => {
        if (!valid) {
          return
        }
        this.editform.selRoleList = []
        this.editform.allRoleList = this.roles
        for (let i = 0; i < this.checkedRoles.length; i++) {
          this.editform.selRoleList.push({
            roleId: this.checkedRoles[i],
            roleName: ''
          })
        }
        let editform = Object.assign({}, this.editform)
        service.post('/user/editwithroles2', editform).then(response => {
          if (response.data.code == 20000) {
            this.$message.success('success!');
            this.editdialogFormVisible = false
            this.load()
          } else {
            this.$message.error("error")
            this.editdialogFormVisible = false
          }
        }).catch(e => {
          console.log(e)
          this.editdialogFormVisible = false
          this.$message.error("保存失败！")
        })
      })

    },
    handleDel(id) {
      service.delete('/user?id=' + id).then(response => {
        this.$message.success('删除成功!');
        this.load()

      })
    },
    search() {
      this.currentPage = 1
      this.load()
    },
    handleDelBatch() {
      console.log(this.$route)
    },
  }
}
</script>

<style scoped>

</style>
